package threadtest;

public class TestThread {

	public static void main(String[] args) {
		new T1().start();
		new T2().start();
		
		while(true) {
			Thread[] f = findAllThreads();
			for (Thread t : f) {
				System.out.println(t);
			}
			System.out.println();
		}
		
	}

	// 下面的静态方法可以用数组返回Java VM中当前运行的所有线程
	public static Thread[] findAllThreads() {
		
		ThreadGroup group = Thread.currentThread().getThreadGroup();
		ThreadGroup topGroup = group;

		// 遍历线程组树，获取根线程组
		while (group != null) {
			topGroup = group;
			group = group.getParent();
		}
		
		// 激活的线程数加倍
		int estimatedSize = topGroup.activeCount() * 2;
		Thread[] slackList = new Thread[estimatedSize];
		
		// 获取根线程组的所有线程
		int actualSize = topGroup.enumerate(slackList);
		
		// copy into a list that is the exact size
		Thread[] list = new Thread[actualSize];
		System.arraycopy(slackList, 0, list, 0, actualSize);
		return list;
	}

	private synchronized static void doSomething(Runnable t) {
		// TODO ....
		System.out.println(t);
	}

	private static void sleepDT(int time) {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
		}
	}

	private static class T1 extends Thread {

		@Override
		public void run() {
			int i = 1000;
			while (--i > 750) {
				sleepDT(100);
				doSomething(this);
			}
		}
	}

	private static class T2 extends Thread {

		@Override
		public void run() {
			long T1 = System.currentTimeMillis();
			long T2 = T1;
			int i = 1000;
			while (--i > 850) {
				if (T2 - T1 >= 100) {
					doSomething(this);
					T1 = System.currentTimeMillis();
				}
				T2 = System.currentTimeMillis();
			}
		}
	}

}
